package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.DictItemManager;
import com.xyzh05.model.DictItem;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class DictItemAction extends BaseAction implements Preparable {
    private DictItemManager dictItemManager;
    private List dictItems;
    private DictItem dictItem;
    private Long id;
    private String query;

    public void setDictItemManager(DictItemManager dictItemManager) {
        this.dictItemManager = dictItemManager;
    }

    public List getDictItems() {
        return dictItems;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String dictItemId = getRequest().getParameter("dictItem.id");
            if (dictItemId != null && !dictItemId.equals("")) {
                dictItem = dictItemManager.get(new Long(dictItemId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        dictItems = dictItemManager.search(query, DictItem.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public DictItem getDictItem() {
        return dictItem;
    }

    public void setDictItem(DictItem dictItem) {
        this.dictItem = dictItem;
    }

    public String delete() {
        dictItemManager.remove(dictItem.getId());
        saveMessage(getText("dictItem.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            dictItem = dictItemManager.get(id);
        } else {
            dictItem = new DictItem();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (dictItem.getId() == null);

        dictItemManager.save(dictItem);

        String key = (isNew) ? "dictItem.added" : "dictItem.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}